﻿using System;
using Pyxis.FluentSelenium.SimpleWebApp.Forum.Domain;

namespace Pyxis.FluentSelenium.SimpleWebApp.Forum
{
    public partial class NewPost1 : System.Web.UI.UserControl
    {
        public event EventHandler SaveOrCancel;

        public int ParentIndex
        {
            get { return ViewState["ParentIndex"] == null ? -1 : Convert.ToInt32(ViewState["ParentIndex"]); }
            set { ViewState["ParentIndex"] = value; }
        }

        protected void btnSavePost_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var post = new Post
                               {
                                   Author = txtAuthor.Text,
                                   Message = txtMessage.Text,
                                   Date = DateTime.Now,
                                   Subject = txtSubject.Text
                               };

                if (HasParent())
                    FakePersistance.Posts[ParentIndex].Replies.Add(post);
                else
                    FakePersistance.Posts.Add(post);

                OnSaveOrCancel();
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            OnSaveOrCancel();
        }

        private void OnSaveOrCancel()
        {
            if (SaveOrCancel != null)
                SaveOrCancel(this, new EventArgs());
        }

        private bool HasParent()
        {
            return ParentIndex != -1;
        }

        public void ClearFields()
        {
            txtAuthor.Text = txtSubject.Text = txtMessage.Text = string.Empty;
        }
    }
}